<template>
  <div class="search-container" :class="theme">
    <!-- 顶部导航 -->
    <TopNav />

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-box">
        <input type="text" v-model="searchQuery" @keyup.enter="searchWord" placeholder="输入要搜索的单词..."
          class="search-input" ref="searchInput">
        <button @click="searchWord" class="search-button">
          <i class="fas fa-search"></i> 搜索
        </button>
      </div>

      <!-- 搜索建议 -->
      <Transition name="fade">
        <div class="suggestions" v-if="suggestions.length > 0">
          <div v-for="(suggestion, index) in suggestions" :key="index" class="suggestion-item"
            @click="selectSuggestion(suggestion)" @mouseenter="hoverSuggestion(index)"
            :class="{ 'suggestion-hover': hoverIndex === index }">
            <span class="suggestion-word">{{ suggestion.word }}</span>
            <span class="suggestion-definition">{{ suggestion.definition }}</span>
          </div>
        </div>
      </Transition>
    </div>

    <!-- 搜索结果 -->
    <div class="results-section" v-if="searchResults">
      <Transition name="slide-fade">
        <div class="word-card" v-if="currentWord">
          <div class="word-header">
            <div class="word-title">
              <h2>{{ currentWord.word }}</h2>
              <span class="phonetic">/{{ currentWord.phonetic }}/</span>
            </div>
            <button class="pronounce-btn" @click="pronounceWord(currentWord.word)" aria-label="发音">
              <i class="fas fa-volume-up"></i>
            </button>
          </div>

          <div class="word-details">
            <div class="detail-section">
              <h3><i class="fas fa-book"></i> 释义</h3>
              <p>{{ currentWord.definition }}</p>
            </div>

            <div class="detail-section" v-if="currentWord.examples && currentWord.examples.length">
              <h3><i class="fas fa-comment"></i> 例句</h3>
              <div class="example" v-for="(example, index) in currentWord.examples" :key="index">
                <p class="example-en">{{ example.en }}</p>
                <p class="example-cn">{{ example.cn }}</p>
              </div>
            </div>

            <div class="detail-section" v-if="currentWord.synonyms && currentWord.synonyms.length">
              <h3><i class="fas fa-exchange-alt"></i> 同义词</h3>
              <div class="synonyms">
                <span v-for="(synonym, index) in currentWord.synonyms" :key="index" @click="searchSynonym(synonym)">
                  {{ synonym }}{{ index < currentWord.synonyms.length - 1 ? '、' : '' }} </span>
              </div>
            </div>
          </div>

          <div class="word-actions">
            <button class="action-btn save-btn" @click="saveWord(currentWord)">
              <i class="fas" :class="isSaved ? 'fa-bookmark' : 'fa-bookmark-o'"></i>
              {{ isSaved ? '已保存' : '保存' }}
            </button>
            <button @click="see_detail(currentWord.word)" class="action-btn practice-btn">
              <i class="fas fa-pen"></i> 查看详细
            </button>
          </div>
        </div>
      </Transition>

      <div class="no-results">
        <i class="fas fa-search-minus"></i>
        <p>没有找到 "{{ searchQuery }}" 的结果</p>
        <button class="retry-btn" @click="focusSearch">重新搜索</button>
      </div>
    </div>

    <!-- 单词抽屉 -->
    <wordDrawerTop :key="selectedWord" :word="selectedWord" :show="showDrawer" @close="showDrawer = false" />

    <!-- 通知提示 -->
    <Transition name="fade">
      <div class="notification" v-if="showNotification">
        {{ notificationMessage }}
      </div>
    </Transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch, inject } from 'vue';
import { useRouter } from 'vue-router';
import wordDrawerTop from "../../components/wordDrawerTop.vue";
import TopNav from "../../components/TopNav.vue";

const router = useRouter();
const searchInput = ref(null);
const searchQuery = ref('');
const searchResults = ref(null);
const suggestions = ref([]);
const currentWord = ref(null);
const hoverIndex = ref(-1);
const savedWords = ref([]);
const showNotification = ref(false);
const notificationMessage = ref('');
const CACHE_KEY = 'excelDataCache';
const SAVED_WORDS_KEY = 'savedWords';

// 主题功能
const theme = inject('theme');
const setTheme = inject('setTheme');

// 加载保存的单词
const loadSavedWords = () => {
  const saved = localStorage.getItem(SAVED_WORDS_KEY);
  if (saved) {
    savedWords.value = JSON.parse(saved);
  }
};

// 检查当前单词是否已保存
const isSaved = computed(() => {
  return currentWord.value
    ? savedWords.value.some(w => w.word === currentWord.value.word)
    : false;
});

// 保存/取消保存单词
const saveWord = (word) => {
  const index = savedWords.value.findIndex(w => w.word === word.word);
  if (index >= 0) {
    savedWords.value.splice(index, 1);
    showNotification1('已从收藏中移除');
  } else {
    savedWords.value.push(word);
    showNotification1('已保存到收藏');
  }
  localStorage.setItem(SAVED_WORDS_KEY, JSON.stringify(savedWords.value));
};

// 显示通知
const showNotification1 = (message) => {
  notificationMessage.value = message;
  showNotification.value = true;
  setTimeout(() => {
    showNotification.value = false;
  }, 2000);
};

// 搜索单词
const searchWord = () => {
  if (!searchQuery.value.trim()) {
    showNotification('请输入搜索内容');
    return;
  }

  // 模拟API调用
  setTimeout(() => {
    const word = searchQuery.value.toLowerCase();
    const mockResults = {
      word: word,
      phonetic: mockPhonetics[word] || 'ˈmɒk.ɪŋ',
      definition: mockDefinitions[word] || 'A word used for demonstration purposes',
      examples: [
        { en: `This is an example sentence using ${word}.`, cn: `这是一个使用${word}的例句。` },
        { en: `Can you think of another sentence with ${word}?`, cn: `你能想出另一个包含${word}的句子吗？` }
      ],
      synonyms: ['demo', 'sample', 'illustration'].filter(s => s !== word)
    };

    currentWord.value = mockResults;
    searchResults.value = true;
    suggestions.value = [];
  }, 300);
};

// 选择搜索建议
const selectSuggestion = (suggestion) => {
  searchQuery.value = suggestion.word;
  searchWord();
  suggestions.value = [];
};

// 搜索同义词
const searchSynonym = (synonym) => {
  searchQuery.value = synonym;
  searchWord();
};

// 发音功能
const pronounceWord = (word) => {
  if ('speechSynthesis' in window) {
    speechSynthesis.cancel();
    const utterance = new SpeechSynthesisUtterance(word);
    utterance.lang = 'en-US';
    utterance.rate = 0.9;
    speechSynthesis.speak(utterance);
  } else {
    showNotification1('您的浏览器不支持语音合成');
  }
};

// 查看详情
const see_detail = (word) => {
  openDrawer(word);
};

// 单词抽屉
const selectedWord = ref("");
const showDrawer = ref(false);

const openDrawer = async (word) => {
  if (showDrawer.value) {
    showDrawer.value = false;
    await nextTick();
  }
  selectedWord.value = word;
  setTimeout(() => {
    showDrawer.value = true;
  }, 10);
};

// 聚焦搜索框
const focusSearch = () => {
  searchInput.value.focus();
};

// 悬停建议项
const hoverSuggestion = (index) => {
  hoverIndex.value = index;
};

// 模拟数据
let mockWords = ['example', 'search', 'word', 'dictionary', 'vocabulary'];
let mockDefinitions = {
  'example': 'a thing characteristic of its kind or illustrating a general rule',
  'search': 'try to find something by looking or otherwise seeking carefully and thoroughly',
  'word': 'a single distinct meaningful element of speech or writing'
};
let mockPhonetics = {
  'example': 'ɪɡˈzɑːm.pəl',
  'search': 'sɜːtʃ',
  'word': 'wɜːd'
};

// 加载缓存数据
const loadFromCache = () => {
  const cached = localStorage.getItem(CACHE_KEY);
  if (cached) {
    try {
      const parsedCache = JSON.parse(cached);
      const decryptedData = JSON.parse(parsedCache.data);

      mockWords = [];
      mockDefinitions = {};
      mockPhonetics = {};

      decryptedData.forEach(item => {
        const [word, definition, phonetic] = item;
        if (word) {
          mockWords.push(word);
          if (definition) mockDefinitions[word] = definition;
          if (phonetic) mockPhonetics[word] = phonetic;
        }
      });
    } catch (error) {
      console.error('数据解析错误:', error);
      resetToDefaultData();
    }
  }
};

// 重置为默认数据
const resetToDefaultData = () => {
  mockWords = ['example', 'search', 'word', 'dictionary', 'vocabulary'];
  mockDefinitions = {
    'example': 'a thing characteristic of its kind or illustrating a general rule',
    'search': 'try to find something by looking or otherwise seeking carefully and thoroughly',
    'word': 'a single distinct meaningful element of speech or writing'
  };
  mockPhonetics = {
    'example': 'ɪɡˈzɑːm.pəl',
    'search': 'sɜːtʃ',
    'word': 'wɜːd'
  };
};

// 监听搜索输入变化
watch(searchQuery, (newVal) => {
  if (newVal.length > 1) {
    try {
      suggestions.value = mockWords
        .filter(word => String(word || '').toLowerCase().includes(newVal.toLowerCase()))
        .map(word => ({
          word: word,
          definition: mockDefinitions[word] || 'A word in the dictionary'
        }))
        .slice(0, 8); // 限制建议数量
    } catch (error) {
      console.error('生成搜索建议时出错:', error);
      suggestions.value = [];
    }
  } else {
    suggestions.value = [];
  }
});

// 组件挂载时初始化
onMounted(() => {
  loadFromCache();
  loadSavedWords();
  focusSearch();
});

const logout = () => {
  localStorage.removeItem('token');
  router.push('/');
};
</script>

<style scoped lang="scss">
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');

.search-container {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  min-height: 100vh;
  padding-bottom: 2rem;
  transition: background-color 0.3s, color 0.3s;
  background-color: var(--bg-color);

  &.light {
    --bg-color: #f8f9fa;
    --text-color: #212529;
    --text-secondary: #495057;
    --border-color: #dee2e6;
    --card-bg: #ffffff;
    --shadow-color: rgba(0, 0, 0, 0.1);
    --hover-color: #f1f3f5;
    --primary-color: #4361ee;
    --success-color: #4cc9f0;
    --warning-color: #f72585;
    --suggestion-bg: #ffffff;
  }

  &.dark {
    --bg-color: #121212;
    --text-color: #e0e0e0;
    --text-secondary: #b0b0b0;
    --border-color: #333333;
    --card-bg: #1e1e1e;
    --shadow-color: rgba(0, 0, 0, 0.3);
    --hover-color: #2d2d2d;
    --primary-color: #3a86ff;
    --success-color: #4cc9f0;
    --warning-color: #f72585;
    --suggestion-bg: #252525;
  }
}

.search-section {
  max-width: 800px;
  margin: 2rem auto;
  padding: 0 1.5rem;
  position: relative;

  .search-box {
    display: flex;
    gap: 0.8rem;
    margin-bottom: 0.5rem;
    position: relative;
  }

  .search-input {
    flex: 1;
    padding: 1rem 1.5rem;
    border: 2px solid var(--border-color);
    border-radius: 12px;
    font-size: 1.1rem;
    background: var(--card-bg);
    color: var(--text-color);
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px var(--shadow-color);

    &:focus {
      outline: none;
      border-color: var(--primary-color);
      box-shadow: 0 2px 15px rgba(74, 107, 255, 0.3);
    }

    &::placeholder {
      color: var(--text-secondary);
      opacity: 0.7;
    }
  }

  .search-button {
    padding: 0 1.8rem;
    background: var(--primary-color);
    color: white;
    border: none;
    border-radius: 12px;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    box-shadow: 0 2px 8px rgba(74, 107, 255, 0.2);

    &:hover {
      background: #3a5bef;
      transform: translateY(-1px);
    }

    &:active {
      transform: translateY(0);
    }

    i {
      margin-right: 0.5rem;
    }
  }
}

.suggestions {
  position: absolute;
  width: 100%;
  max-height: 300px;
  overflow-y: auto;
  background: var(--suggestion-bg);
  border-radius: 0 0 12px 12px;
  box-shadow: 0 5px 15px var(--shadow-color);
  z-index: 10;
  border: 2px solid var(--border-color);
  border-top: none;
}

.suggestion-item {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid var(--border-color);
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  flex-direction: column;

  &:last-child {
    border-bottom: none;
  }

  &:hover,
  &.suggestion-hover {
    background: var(--hover-color);
  }
}

.suggestion-word {
  font-weight: 600;
  color: var(--primary-color);
  margin-bottom: 0.3rem;
}

.suggestion-definition {
  font-size: 0.9rem;
  color: var(--text-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.results-section {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 1.5rem;
}

.word-card {
  background: var(--card-bg);
  border-radius: 16px;
  box-shadow: 0 5px 20px var(--shadow-color);
  padding: 2rem;
  margin-top: 1.5rem;
  transition: all 0.3s;
  border: 1px solid var(--border-color);
}

.word-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid var(--border-color);

  .word-title {
    h2 {
      margin: 0;
      font-size: 2.2rem;
      color: var(--primary-color);
      text-transform: capitalize;
      line-height: 1.2;
    }

    .phonetic {
      display: block;
      margin-top: 0.3rem;
      color: var(--text-secondary);
      font-style: italic;
      font-size: 1.1rem;
    }
  }

  .pronounce-btn {
    background: var(--hover-color);
    border: none;
    width: 48px;
    height: 48px;
    border-radius: 50%;
    color: var(--primary-color);
    font-size: 1.3rem;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background: var(--primary-color);
      color: white;
      transform: scale(1.05);
    }

    &:active {
      transform: scale(0.98);
    }
  }
}

.word-details {
  .detail-section {
    margin-bottom: 2rem;

    &:last-child {
      margin-bottom: 0;
    }

    h3 {
      display: flex;
      align-items: center;
      color: var(--primary-color);
      margin: 0 0 1rem;
      font-size: 1.2rem;

      i {
        margin-right: 0.8rem;
        font-size: 1.1rem;
      }
    }

    p {
      margin: 0.5rem 0;
      line-height: 1.7;
      color: var(--text-color);
      font-size: 1.05rem;
    }
  }

  .example {
    background: var(--hover-color);
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 1rem;
    transition: all 0.3s;

    &:hover {
      transform: translateX(3px);
    }

    &-en {
      font-weight: 500;
      margin-bottom: 0.5rem;
      color: var(--text-color);
    }

    &-cn {
      color: var(--text-secondary);
      font-size: 0.95rem;
    }
  }

  .synonyms {
    display: flex;
    flex-wrap: wrap;
    gap: 0.6rem;

    span {
      background: var(--hover-color);
      padding: 0.4rem 1rem;
      border-radius: 20px;
      font-size: 0.95rem;
      color: var(--text-color);
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background: var(--primary-color);
        color: white;
      }
    }
  }
}

.word-actions {
  display: flex;
  gap: 1rem;
  margin-top: 2.5rem;

  .action-btn {
    flex: 1;
    padding: 1rem;
    border: none;
    border-radius: 12px;
    font-weight: 600;
    font-size: 1rem;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;

    i {
      margin-right: 0.8rem;
      font-size: 1.1rem;
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px var(--shadow-color);
    }

    &:active {
      transform: translateY(0);
    }
  }

  .save-btn {
    background: rgba(25, 118, 210, 0.1);
    color: #1976d2;

    &:hover {
      background: rgba(25, 118, 210, 0.2);
    }
  }

  .practice-btn {
    background: rgba(56, 142, 60, 0.1);
    color: #388e3c;

    &:hover {
      background: rgba(56, 142, 60, 0.2);
    }
  }
}

.no-results {
  text-align: center;
  padding: 3rem 2rem;
  background: var(--card-bg);
  border-radius: 16px;
  box-shadow: 0 5px 20px var(--shadow-color);
  margin-top: 1.5rem;

  i {
    font-size: 3.5rem;
    color: var(--text-secondary);
    margin-bottom: 1.5rem;
    opacity: 0.7;
  }

  p {
    font-size: 1.3rem;
    color: var(--text-secondary);
    margin-bottom: 2rem;
  }

  .retry-btn {
    padding: 0.8rem 2rem;
    background: var(--primary-color);
    color: white;
    border: none;
    border-radius: 8px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background: #3a5bef;
      transform: translateY(-2px);
    }
  }
}

.notification {
  position: fixed;
  bottom: 2rem;
  left: 50%;
  transform: translateX(-50%);
  background: var(--primary-color);
  color: white;
  padding: 1rem 2rem;
  border-radius: 8px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  z-index: 100;
  font-weight: 500;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateY(20px);
  opacity: 0;
}

@media (max-width: 768px) {
  .search-section {
    padding: 0 1rem;
  }

  .search-box {
    flex-direction: column;
    gap: 0.8rem;
  }

  .word-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;

    .word-title h2 {
      font-size: 1.8rem;
    }
  }

  .word-actions {
    flex-direction: column;
  }
}
</style>